'use strict';
const express = require('express');
const router = express.Router();
const extend = require('extend');

const resUtil = require("../module/util/resUtil");

const QRCode = require('qrcode');
const md5 = require('md5');
const log4js = require('log4js');
let logger = log4js.getLogger("qrCode");

let date2string = function(date, format){
    format = format || thisTool.defaults.date.dateFormat;
    var o = {
        "M+" : date.getMonth() + 1, //month
        "d+" : date.getDate(),      //day
        "h+" : date.getHours(),     //hour
        "m+" : date.getMinutes(),   //minute
        "s+" : date.getSeconds(),   //second
        "w+" : "天一二三四五六".charAt(date.getDay()),   //week
        "q+" : Math.floor((date.getMonth() + 3) / 3),  //quarter
        "S"  : date.getMilliseconds() //millisecond
    };
    if(/(y+)/.test(format)) {
        format = format.replace(RegExp.$1,
            (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for(var k in o){
        if(new RegExp("("+ k +")").test(format)){
            format = format.replace(RegExp.$1,
                RegExp.$1.length == 1 ? o[k] :
                    ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return format;
};

/* GET home page. */
router.get('/', function(req, res, next) {
    let wx = 'wx';
    let alias = '';
    // let email = (req.session.userData && req.session.userData.email);
    let email = '494297161@qq.com';
    if(email){
        alias = email.substr(0, email.indexOf('@'));
    }
    let now = new Date();
    let time = date2string(now, 'yyMMddhhmmss');
    let OrderNo = alias+time;
    let SecureCode = md5(md5(alias+time+OrderNo).substring(4, 20)).substr(26);

    let qrStr = wx+alias+time+OrderNo+SecureCode;
    global.cache.qrCode[OrderNo] = {
        state : 'create',
        time : now,
        alias : alias,
        OrderNo : OrderNo,
        qrCode : qrStr,
    };
    setTimeout(() => {
        if(global.cache.qrCode[OrderNo]){
            delete global.cache.qrCode[OrderNo];
        }
    }, 600000);
    console.log(OrderNo);
    QRCode.toDataURL(qrStr, function (err, url) {
        res.send(resUtil.success({data: url, code: qrStr, orderNo: OrderNo}));
    })
});

/**
 * flowId: Pos端的交易流水号
 * orderNo：订单号
 * amount：金额
 * alias: 用户标识
 * happenTime： 交易时间，格式为yyyy-mm-dd hh:mm:ss
 * success: 交易状态：0-失败 1-成功
 * remark：此次交易的描述
 * terminal：本次交易的终端号
 */
router.get('/confirm', function(req, res, next) {
    // let data = req.body;
    let data = req.query;
    if(global.cache.qrCode[data.orderNo]){
        logger.info('qrCodeCallback', data.orderNo, data);
        global.cache.qrCode[data.orderNo].state = 'success';
        res.send(resUtil.success());
    }else{
        res.send(resUtil.error({message:'can not find this order no'}));
    }
});

router.get('/getState/:orderNo', function(req, res, next) {
    // let data = req.body;
    let orderNo = req.params.orderNo;
    if(global.cache.qrCode[orderNo]){
        //TODO 回调成功后，页面提示信息
        res.send(resUtil.success({data: global.cache.qrCode[orderNo].state, message:'回调成功'}));
    }else{
        res.send(resUtil.error({message:'can not find this order no'}));
    }
});

module.exports = router;
